//
//  RobotSystem.m
//  RobotCleaner
//
//  Created by hcl on 2022/5/19.
//

#import "RobotSystem.h"
#import "HeaderConfig.h"

static RobotSystem *instance = nil;
static NSString *appVer = nil;

@implementation RobotSystem

+ (instancetype)shareInstance;
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
      instance = [[RobotSystem alloc] init];
    });

    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}

+ (void)dispatch_asyn_main:(void (^)(void))call NS_AVAILABLE(10_7, 5_0) {
    dispatch_async(dispatch_get_main_queue(), ^{
      call();
    });
}

+ (CGFloat)getlabeHeight:(UIFont *)font text:(NSString *)text width:(CGFloat)width {
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 10000)];
    lab.numberOfLines = 0;
    lab.font = font;
    lab.text = text;
    [lab sizeToFit];
    return lab.frame.size.height;
}

+ (CGFloat)getlabeWidth:(UIFont *)font text:(NSString *)text {
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 10000, 10000)];
    lab.numberOfLines = 0;
    lab.font = font;
    lab.text = text;
    [lab sizeToFit];
    return lab.frame.size.width;
}

+ (void)callServerPhone:(NSString *)phoneNumber fromVC:(UIViewController *)vc {
    if (judgeStringIsNULL(phoneNumber)) return;
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", phoneNumber]];
    [[UIApplication sharedApplication] openURL:url];
}

// 获取当前verison
+ (NSString *)getCurrentVersion {
    if (!judgeStringIsNULL(appVer)) return appVer;
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    appVer = app_Version;
    return app_Version;
}

+ (double)calculateCodeExecuteTime:(void (^)(void))executeBlock {
    if (executeBlock) {
        CFTimeInterval start = CFAbsoluteTimeGetCurrent();
        executeBlock();
        CFTimeInterval end = CFAbsoluteTimeGetCurrent();
        CFTimeInterval dur = end - start;
        printf("***>>>\nexecuteTime:%lf", dur);
        return dur;
    }
    return 0.f;
}

/**
 对字典(Key-Value)排序 区分大小写

 @param dict 要排序的字典
 */
NSArray *sortedDictionary(NSDictionary *dict) {
    if (judgeDictionaryIsNULL(dict)) return @[ @[], @[] ];
    // 将所有的key放进数组
    NSArray *allKeyArray = [dict allKeys];
    NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
      /* compare方法的比较原理为,依次比较当前字符串的第一个字母: 如果不同,按照输出排序结果 如果相同,依次比较当前字符串的下一个字母(这里是第二个) 以此类推 排序结果 NSComparisonResult resuest = [obj1 compare:obj2];为从小到大,即升序; NSComparisonResult resuest = [obj2 compare:obj1];为从大到小,即降序; 注意:compare方法是区分大小写的,即按照ASCII排序*/
      // 排序操作
      NSComparisonResult resuest = [obj1 compare:obj2];
      return resuest;
    }];
    // 序列化器对数组进行排序的block 返回值为排序后的数组
    //     NSLog(@"afterSortKeyArray:%@",afterSortKeyArray);
    // 通过排列的key值获取value
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortsing in afterSortKeyArray) {
        id valueString = [dict objectForKey:sortsing];
        NSString *vaStr = @"";
        if ([valueString isKindOfClass:[NSNumber class]]) {
            NSNumber *num = (NSNumber *)valueString;
            vaStr = [NSString stringWithFormat:@"%@", num];
        } else if ([valueString isKindOfClass:[NSString class]]) {
            vaStr = valueString;
        }
        [valueArray addObject:vaStr];
    }
    if (valueArray.count != afterSortKeyArray.count) return @[ @[], @[] ];
    NSMutableArray *kvArr = [[NSMutableArray alloc] initWithCapacity:0];
    [kvArr addObject:afterSortKeyArray];
    [kvArr addObject:valueArray];
    return kvArr.copy;
}

NSString *securityString(id obj) {
    if ([obj isKindOfClass:[NSString class]]) {
        return obj;
    } else if ([obj isKindOfClass:[NSNumber class]]) {
        NSNumber *num = (NSNumber *)obj;
        return [NSString stringWithFormat:@"%@", num.stringValue];
    } else {
        return @"";
    }
}

NSArray *securityArray(id obj) {
    if ([obj isKindOfClass:[NSArray class]]) {
        return obj;
    } else {
        return @[];
    }
}

NSDictionary *securityDictionary(id obj) {
    if ([obj isKindOfClass:[NSDictionary class]]) {
        return obj;
    } else {
        return @{};
    }
}

/**  对一个字符串进行base64编码，并返回  */
NSString *base64EncodeString(id obj) {
    if (judgeStringIsNULL(obj)) return @"";
    // 1、先转换成二进制数据
    NSData *data = [obj dataUsingEncoding:NSUTF8StringEncoding];
    // 2、对二进制数据进行base64编码，完成后返回字符串
    return [data base64EncodedStringWithOptions:0];
}

/**  对一个base64编码后的字符串解码  */
NSString *base64DecodeString(id obj) {
    if (judgeStringIsNULL(obj)) return @"";
    // 注意：该字符串是base64编码后的字符串
    // 1、转换为二进制数据（完成了解码的过程）
    NSData *data = [[NSData alloc] initWithBase64EncodedString:securityString(obj) options:0];
    // 2、把二进制数据转换成字符串
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

/**  指定范围内的随机数 仅支持正整数 */
NSInteger getRandomNumberFrom(NSInteger fromNum, NSInteger toNum) {
    if (fromNum == toNum) return 0;
    NSInteger to = toNum > fromNum ? toNum : fromNum;
    NSInteger from = toNum < fromNum ? toNum : fromNum;
    return (NSInteger)(from + (arc4random() % (to - from + 1)));
}

/**  获取n位随机数 0~9 a~z A~Z  最大为256位*/
NSString *getRandomNumberWithX_Length(int length) {
    if (length <= 0) return @"";
    NSArray *seedArr = @[ @"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", @"i", @"j", @"k", @"l", @"m", @"n", @"o", @"p", @"q", @"r", @"s", @"t", @"u", @"v", @"w", @"x", @"y", @"z", @"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z" ];
    length = length > 256 ? 256 : length;
    NSString *resultStr = @"";
    for (int i = 0; i < length; i++) {
        NSInteger index = arc4random() % seedArr.count;
        resultStr = [resultStr stringByAppendingString:seedArr[index]];
    }
    return resultStr;
}

/**  通过归解档来深拷贝数组  */
NSArray *trueDeepCopyArray(id obj) {
    NSArray *oldArray = securityArray(obj);
    NSArray *trueDeepCopyArray = [NSKeyedUnarchiver unarchiveObjectWithData:
                                                        [NSKeyedArchiver archivedDataWithRootObject:oldArray]];
    return trueDeepCopyArray;
}

/**  字典转Json字符串  */
NSString *dicConvertToJsonString(id infoDict) {
    if (judgeDictionaryIsNULL(infoDict)) return @"";
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict
                                                       options:NSJSONWritingSortedKeys
                                                         error:&error];
    NSString *jsonString = @"";
    if (!jsonData) {
        NSLog(@"Got an error: %@", error);
        return @"";
    }

    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    // 去除掉首尾的空白字符和换行字符
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return securityString(jsonString);
}

/**  JSON字符串转化为字典  */
NSDictionary *jsonStringConvertToDic(NSString *jsonString) {
    if (judgeStringIsNULL(jsonString)) return @{};
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    id dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                             options:NSJSONReadingMutableContainers
                                               error:&err];
    if (err) {
        NSLog(@"json解析失败：%@", err);
        return @{};
    }
    return securityDictionary(dic);
}

// 剔除空格
NSString *trimmingWhitespaceWith(NSString *str) {
    if (!judgeStringIsNULL(str)) {
        return [[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    return @"";
}

/**  小数转换为NSString  */
NSString *getStringFromDoubleVal(double doubleVal) {
    NSString *stringValue = @"0.00";
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.usesSignificantDigits = true;
    formatter.maximumSignificantDigits = 100;
    formatter.groupingSeparator = @"";
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    stringValue = [formatter stringFromNumber:@(doubleVal)];
    return stringValue;
}

/**  保留n位小数不四舍五入  */
NSString *getStringFromFloatVal(double floatVal, int decimalsLength) {
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.roundingMode = NSNumberFormatterRoundFloor;
    formatter.maximumFractionDigits = decimalsLength;
    formatter.minimumIntegerDigits = 1;
    return [formatter stringFromNumber:@(floatVal)];
}

// 限制字符串长度为  limit 并且拼接...
NSString *limtStringWithTrail(NSString *str, NSInteger limit) {
    if (!judgeStringIsNULL(str)) {
        if (str.length > limit) {
            str = [[str substringToIndex:limit] stringByAppendingString:@"..."];
            return str;
        } else {
            return str;
        }
    }
    return @"";
}

/*! @brief 限制数字输入
 @ para maxNum 最大数字
 @ para decimalsLength 小数的长度
 *
 */
void limitInputNumber(UITextField *textField, NSString *maxNum, int decimalsLength) {
    NSString *moneyStr = textField.text;
    if (!judgeStringIsNULL(maxNum)) {
        if (maxNum.floatValue <= 0) {
            return;
        }
        if ([moneyStr hasPrefix:maxNum]) {
            textField.text = maxNum;
        } else {
            if ([moneyStr floatValue] > maxNum.floatValue) {
                NSMutableString *str = [NSMutableString stringWithString:moneyStr];
                if ([str containsString:@"."]) {
                    NSRange range = [moneyStr rangeOfString:@"0."];
                    moneyStr = [moneyStr substringFromIndex:range.location];
                    textField.text = [NSString stringWithFormat:@"%@", moneyStr];
                } else {
                    while ([str hasPrefix:@"0"]) {
                        [str deleteCharactersInRange:NSMakeRange(0, 1)];
                    }
                    NSString *subStr = [str substringToIndex:str.length - 1];
                    textField.text = subStr;
                }
            } else {
                if (decimalsLength <= 0) {
                    moneyStr = [moneyStr stringByReplacingOccurrencesOfString:@"." withString:@""];
                    textField.text = moneyStr;
                }
                if ([moneyStr containsString:@"."]) {    // 只能输入小数点后 decimalsLength 位
                    NSArray *arr = [moneyStr componentsSeparatedByString:@"."];
                    if (arr.count > 2) {
                        NSString *decimals = arr[1];
                        NSString *integerStr = arr.firstObject;
                        moneyStr = [[integerStr stringByAppendingString:@"."] stringByAppendingString:decimals];
                        textField.text = [NSString stringWithFormat:@"%@", moneyStr];
                    } else {
                        NSString *decimals = arr[1];
                        if (decimals.length > decimalsLength) {
                            NSString *subStr = [decimals substringToIndex:decimalsLength];
                            NSString *integerStr = arr.firstObject;
                            moneyStr = [[integerStr stringByAppendingString:@"."] stringByAppendingString:subStr];
                            textField.text = [NSString stringWithFormat:@"%@", moneyStr];
                        }
                    }
                    if ([moneyStr hasPrefix:@"00"]) {
                        NSRange range = [moneyStr rangeOfString:@"0."];
                        moneyStr = [moneyStr substringFromIndex:range.location];
                        textField.text = [NSString stringWithFormat:@"%@", moneyStr];
                    }
                }
            }
        }
    } else {
        if (decimalsLength <= 0) {
            moneyStr = [moneyStr stringByReplacingOccurrencesOfString:@"." withString:@""];
            textField.text = moneyStr;
        }
        if ([moneyStr containsString:@"."]) {    // 只能输入小数点后 decimalsLength 位
            NSArray *arr = [moneyStr componentsSeparatedByString:@"."];
            if (arr.count > 2) {
                NSString *decimals = arr[1];
                NSString *integerStr = arr.firstObject;
                moneyStr = [[integerStr stringByAppendingString:@"."] stringByAppendingString:decimals];
                textField.text = [NSString stringWithFormat:@"%@", moneyStr];
            } else {
                NSString *decimals = arr[1];
                if (decimals.length > decimalsLength) {
                    NSString *subStr = [decimals substringToIndex:decimalsLength];
                    NSString *integerStr = arr.firstObject;
                    moneyStr = [[integerStr stringByAppendingString:@"."] stringByAppendingString:subStr];
                    textField.text = [NSString stringWithFormat:@"%@", moneyStr];
                }
            }
            if ([moneyStr hasPrefix:@"00"]) {
                NSRange range = [moneyStr rangeOfString:@"0."];
                moneyStr = [moneyStr substringFromIndex:range.location];
                textField.text = [NSString stringWithFormat:@"%@", moneyStr];
            }
        }
    }
}

/*! @brief 限制数字输入
 @ para maxNum 最大数字
 @ para decimalsLength 小数的长度
 @ para moreThanMaxNumberBlock 超过最大数字时的block
 @ para moreThanDecimalsLengthBlock 超过最小数长度时的block
 *
 */
void limitInputNumberWihthBlock(UITextField *textField, NSString *maxNum, int decimalsLength, void (^moreThanMaxNumberBlock)(void), void (^moreThanDecimalsLengthBlock)(void)) {
    NSString *moneyStr = textField.text;
    if (!judgeStringIsNULL(maxNum)) {
        if (maxNum.floatValue <= 0) {
            return;
        }
        if ([moneyStr hasPrefix:maxNum]) {
            if ([moneyStr floatValue] > maxNum.floatValue) {
                if (moreThanMaxNumberBlock) {
                    moreThanMaxNumberBlock();
                }
            }
            textField.text = maxNum;
        } else {
            if ([moneyStr floatValue] > maxNum.floatValue) {
                NSMutableString *str = [NSMutableString stringWithString:moneyStr];
                if ([str containsString:@"."]) {
                    moneyStr = [moneyStr substringToIndex:moneyStr.length - 1];
                    textField.text = [NSString stringWithFormat:@"%@", moneyStr];
                    if (moreThanMaxNumberBlock) {
                        moreThanMaxNumberBlock();
                    }
                } else {
                    while ([str hasPrefix:@"0"]) {
                        [str deleteCharactersInRange:NSMakeRange(0, 1)];
                    }
                    NSString *subStr = [str substringToIndex:str.length - 1];
                    textField.text = subStr;
                    if (moreThanMaxNumberBlock) {
                        moreThanMaxNumberBlock();
                    }
                }
            } else {
                if (decimalsLength <= 0) {
                    moneyStr = [moneyStr stringByReplacingOccurrencesOfString:@"." withString:@""];
                    textField.text = moneyStr;
                }
                if ([moneyStr containsString:@"."]) {    // 只能输入小数点后 decimalsLength 位
                    NSArray *arr = [moneyStr componentsSeparatedByString:@"."];
                    if (arr.count > 2) {
                        NSString *decimals = arr[1];
                        NSString *integerStr = arr.firstObject;
                        moneyStr = [[integerStr stringByAppendingString:@"."] stringByAppendingString:decimals];
                        textField.text = [NSString stringWithFormat:@"%@", moneyStr];
                    } else {
                        NSString *decimals = arr[1];
                        if (decimals.length > decimalsLength) {
                            NSString *subStr = [decimals substringToIndex:decimalsLength];
                            NSString *integerStr = arr.firstObject;
                            moneyStr = [[integerStr stringByAppendingString:@"."] stringByAppendingString:subStr];
                            textField.text = [NSString stringWithFormat:@"%@", moneyStr];
                            if (moreThanDecimalsLengthBlock) {
                                moreThanDecimalsLengthBlock();
                            }
                        }
                    }
                    if ([moneyStr hasPrefix:@"00"]) {
                        NSRange range = [moneyStr rangeOfString:@"0."];
                        moneyStr = [moneyStr substringFromIndex:range.location];
                        textField.text = [NSString stringWithFormat:@"%@", moneyStr];
                    }
                }
            }
        }
    } else {    // 判断小数长度的代码
        if (decimalsLength <= 0) {
            moneyStr = [moneyStr stringByReplacingOccurrencesOfString:@"." withString:@""];
            textField.text = moneyStr;
        }
        if ([moneyStr containsString:@"."]) {    // 只能输入小数点后 decimalsLength 位
            NSArray *arr = [moneyStr componentsSeparatedByString:@"."];
            if (arr.count > 2) {
                NSString *decimals = arr[1];
                NSString *integerStr = arr.firstObject;
                moneyStr = [[integerStr stringByAppendingString:@"."] stringByAppendingString:decimals];
                textField.text = [NSString stringWithFormat:@"%@", moneyStr];
            } else {
                NSString *decimals = arr[1];
                if (decimals.length > decimalsLength) {
                    NSString *subStr = [decimals substringToIndex:decimalsLength];
                    NSString *integerStr = arr.firstObject;
                    moneyStr = [[integerStr stringByAppendingString:@"."] stringByAppendingString:subStr];
                    textField.text = [NSString stringWithFormat:@"%@", moneyStr];
                    if (moreThanDecimalsLengthBlock) {
                        moreThanDecimalsLengthBlock();
                    }
                }
            }
            if ([moneyStr hasPrefix:@"00"]) {
                NSRange range = [moneyStr rangeOfString:@"0."];
                moneyStr = [moneyStr substringFromIndex:range.location];
                textField.text = [NSString stringWithFormat:@"%@", moneyStr];
            }
        }
    }
}

/*! @brief 限制货币8位小数
 *
 */
NSString *limitHuoBiNumber(id obj) {
    NSString *numStr = @"0";
    if ([obj isKindOfClass:[NSNumber class]]) {
        NSNumber *num = (NSNumber *)obj;
        numStr = [NSString stringWithFormat:@"%.8lf", num.doubleValue];
    } else if ([obj isKindOfClass:[NSString class]]) {
        NSString *num = (NSString *)obj;
        numStr = [NSString stringWithFormat:@"%.8lf", num.doubleValue];
    }
    return numStr;
}

// 按分割长度 和分割字符(默认封符@“ ”) 来分割字符长
NSString *segmentationString(NSString *str, NSInteger blockLengtn, NSString *insertStr) {
    if (judgeStringIsNULL(str)) return @"";
    if (blockLengtn <= 0) return str;
    if (str.length <= blockLengtn) return str;
    NSString *temInsetStr = @"";
    if (judgeStringIsNULL(insertStr)) {
        temInsetStr = @" ";
    } else {
        temInsetStr = insertStr;
    }
    NSMutableString *mstr = str.mutableCopy;
    CGFloat den = (CGFloat)str.length / blockLengtn;
    NSInteger n = str.length / blockLengtn;
    NSInteger forTimes = 0;
    if (den - n > 0) {
        forTimes = n;
    } else {
        forTimes = n - 1;
    }
    for (int i = 0; i < forTimes; i++) {
        NSInteger index = i * (blockLengtn + temInsetStr.length) + blockLengtn;
        [mstr insertString:temInsetStr atIndex:index];
    }
    return mstr.copy;
}

/*
 手机号码合法性验证
 */
BOOL isValidTelNumber(id numberStr) {
    NSString *phoen = @"";
    if ([numberStr isKindOfClass:[NSNumber class]]) {
        NSNumber *num = (NSNumber *)numberStr;
        phoen = [NSString stringWithFormat:@"%@", num];
    } else if ([numberStr isKindOfClass:[NSString class]]) {
        phoen = numberStr;
    }
    phoen = trimmingWhitespaceWith(phoen);    // 去空
    if (judgeStringIsNULL(phoen)) return NO;
    NSString *MOBILE = @"^1[0-9]{10}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    return [regextestmobile evaluateWithObject:phoen];
}

// 转换为安全手机号 例如138****6689
NSString *stringConvertToSecretMobile(NSString *mobileStr) {
    if (!isValidTelNumber(mobileStr)) return securityString(mobileStr);    // 如果不是手机号 或为空 直接返回
    return [trimmingWhitespaceWith(mobileStr) stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
}

// 用户名转换
NSString *usernameConvertToSecretMobile(NSString *name, NSInteger limte) {
    if (!isValidTelNumber(name)) {    // 如果不是手机号 或为空 直接返回
        return judgeStringIsNULL(name) ? @"" : name.length > limte ? [[name substringToIndex:limte] stringByAppendingString:@"..."]
                                                                   : name;
    } else {
        return [trimmingWhitespaceWith(name) stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }
}

NSMutableAttributedString *priceAttStringWithScoreString(NSString *priceStr, UIFont *integerFont, UIFont *decimalFont) {
    if (judgeStringIsNULL(priceStr)) {
        priceStr = @"0";
    }
    NSString *temPriceStr = [NSString stringWithFormat:@"%.2f", [priceStr floatValue]];
    NSInteger len = temPriceStr.length;
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:temPriceStr];
    [string addAttribute:NSFontAttributeName value:integerFont range:NSMakeRange(0, len - 3)];
    [string addAttribute:NSFontAttributeName value:decimalFont range:NSMakeRange(len - 2, 2)];
    return string;
}

NSMutableAttributedString *priceAttStringWithScoreStringAndSymbol(NSString *symbol, NSString *priceStr, UIFont *symbolFont, UIFont *integerFont, UIFont *decimalFont) {
    if (judgeStringIsNULL(priceStr)) {
        priceStr = @"0";
    }
    NSMutableAttributedString *sourceText = [NSMutableAttributedString new];

    NSString *temSymbo = judgeStringIsNULL(symbol) ? @"" : [symbol stringByAppendingString:@" "];
    NSMutableAttributedString *symbolStr = [[NSMutableAttributedString alloc] initWithString:temSymbo];
    if (symbolFont) {
        [symbolStr addAttribute:NSFontAttributeName value:symbolFont range:NSMakeRange(0, symbolStr.length)];
    }
    [sourceText appendAttributedString:symbolStr];

    NSString *temPriceStr = [NSString stringWithFormat:@"%.2f", [priceStr floatValue]];
    NSInteger len = temPriceStr.length;
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:temPriceStr];
    [string addAttribute:NSFontAttributeName value:integerFont range:NSMakeRange(0, len - 3)];
    [string addAttribute:NSFontAttributeName value:decimalFont range:NSMakeRange(len - 2, 2)];
    [sourceText appendAttributedString:string];
    return sourceText;
}

NSMutableAttributedString *priceAttStringWithScoreStringAndSymbolwithcoloer(NSString *symbol, NSString *priceStr, UIFont *symbolFont, UIFont *integerFont, UIFont *decimalFont, UIColor *textCorlor) {
    if (judgeStringIsNULL(priceStr)) {
        priceStr = @"0";
    }
    NSMutableAttributedString *sourceText = [NSMutableAttributedString new];

    NSString *temSymbo = judgeStringIsNULL(symbol) ? @"" : [symbol stringByAppendingString:@" "];
    NSMutableAttributedString *symbolStr = [[NSMutableAttributedString alloc] initWithString:temSymbo];
    if (symbolFont) {
        [symbolStr addAttribute:NSFontAttributeName value:symbolFont range:NSMakeRange(0, symbolStr.length)];
    }
    [sourceText appendAttributedString:symbolStr];

    NSString *temPriceStr = [NSString stringWithFormat:@"%.2f", [priceStr floatValue]];
    NSInteger len = temPriceStr.length;
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:temPriceStr];
    [string addAttribute:NSFontAttributeName value:integerFont range:NSMakeRange(0, len - 3)];
    [string addAttribute:NSFontAttributeName value:decimalFont range:NSMakeRange(len - 2, 2)];
    [sourceText appendAttributedString:string];
    [sourceText addAttribute:NSForegroundColorAttributeName value:textCorlor range:NSMakeRange(0, sourceText.length)];

    return sourceText;
}

NSString *shortedNumberDesc(id numberStr) {
    NSInteger number = 0;
    if ([numberStr isKindOfClass:[NSNumber class]]) {
        NSNumber *num = (NSNumber *)numberStr;
        number = num.longLongValue;
    } else {
        if (judgeStringIsNULL(numberStr)) return @"0";
        NSString *nStr = (NSString *)numberStr;
        number = nStr.integerValue;
    }
    if (number <= 0) return @"0";
    if (number <= 9999) return [NSString stringWithFormat:@"%d", (int)number];
    if (number <= 9999999) {
        double num = (double)number / 10000;
        return [NSString stringWithFormat:@"%.1lf万", num];
    }
    return [NSString stringWithFormat:@"%.1lf千万", (double)((double)number / 10000000)];
}

BOOL judgeIsNULL(id obj) {
    if ([obj isKindOfClass:[NSString class]]) {
        NSString *temp = obj;
        if (temp == nil || temp.length == 0) return YES;
        return NO;
    } else if ([obj isKindOfClass:[NSArray class]]) {
        NSArray *temp = obj;
        if (temp == nil || temp.count == 0) return YES;
        return NO;
    } else if ([obj isKindOfClass:[NSDictionary class]]) {
        NSDictionary *temp = obj;
        if (temp == nil || temp.count == 0) return YES;
        return NO;
    } else if ([obj isKindOfClass:[NSNull class]]) {
        return YES;
    } else if (obj == nil) {
        return YES;
    }
    return NO;
}

BOOL judgeStringIsNULL(id obj) {
    if ([obj isKindOfClass:[NSString class]]) {
        NSString *temp = obj;
        if (temp == nil || temp.length == 0) return YES;
        return NO;
    } else if ([obj isKindOfClass:[NSNull class]]) {
        return YES;
    } else if (obj == nil) {
        return YES;
    } else if ([obj isEqualToString:@"<null>"]) {
        return YES;
    } else {
        return YES;
    }
}

BOOL judgeArrayIsNULL(id obj) {
    if ([obj isKindOfClass:[NSArray class]]) {
        NSArray *temp = obj;
        if (temp == nil || temp.count == 0) return YES;
        return NO;
    } else if ([obj isKindOfClass:[NSNull class]]) {
        return YES;
    } else if (obj == nil) {
        return YES;
    } else {
        return YES;
    }
}

BOOL judgeDictionaryIsNULL(id obj) {
    if ([obj isKindOfClass:[NSDictionary class]]) {
        NSDictionary *temp = obj;
        if (temp == nil || temp.count == 0) return YES;
        return NO;
    } else if ([obj isKindOfClass:[NSNull class]]) {
        return YES;
    } else if (obj == nil) {
        return YES;
    } else {
        return YES;
    }
}

UIImage *imageScaleToWidth(UIImage *originImg, CGFloat width) {
    if (originImg == nil) return nil;

    // 如果传入的宽度比当前宽度还要大,就直接返回
    if (width > originImg.size.width) return originImg;

    // 计算缩放之后的高度
    CGFloat height = (width / originImg.size.width) * originImg.size.height;

    // 初始化要画的大小
    CGRect rect = CGRectMake(0, 0, width, height);

    // 1. 开启图形上下文
    UIGraphicsBeginImageContext(rect.size);

    // 2. 画到上下文中 (会把当前image里面的所有内容都画到上下文)
    [originImg drawInRect:rect];

    // 3. 取到图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // 4. 关闭上下文
    UIGraphicsEndImageContext();
    // 5. 返回
    return image;
}

// 画水印
UIImage *imageWithWaterMask(UIImage *originImg, UIImage *mask, CGRect inRect) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0) {
        UIGraphicsBeginImageContext([originImg size]);    // 0.0 for scale means "scale for device's main screen".
    }
#else
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 4.0) {
        UIGraphicsBeginImageContext([originImg size]);
    }
#endif
    // 原图
    [originImg drawInRect:CGRectMake(0, 0, originImg.size.width, originImg.size.height)];
    // 水印图
    [mask drawInRect:inRect];
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newPic;
}

#pragma mark---封装系统弹框

// message文本对齐 且可选择是弹框方式还是底部弹出选择方式
+ (void)alert_tip:(NSString *)title andMessage:(NSString *)message andcancel:(NSString *)cancel_title andcancelColor:(UIColor *)cancelColor andsure:(NSString *)sure_title andsureColor:(UIColor *)sureColor andviewController:(UIViewController *)vc andsure_click:(sure_click)sure_click_block andcancel_click:(cancel_click)cancel_click_block andtitleAlignment:(NSTextAlignment)title_alignment andmessage_textAlignment:(NSTextAlignment)text_alignment andpreferredStyle:(UIAlertControllerStyle)preferredStyle {
    UIAlertController *alert_vc = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:preferredStyle];

    // 修改title 对齐方式
    UIView *subView1 = alert_vc.view.subviews[0];
    UIView *subView2 = subView1.subviews[0];
    UIView *subView3 = subView2.subviews[0];
    UIView *subView4 = subView3.subviews[0];
    UIView *subView5 = subView4.subviews[0];
    NSLog(@"%@", subView5.subviews);
    // 取title和message：

    if (preferredStyle == 1) {
        if ([subView5.subviews[1] isKindOfClass:[UILabel class]]) {
            UILabel *alert_vc_message = subView5.subviews[1];
            alert_vc_message.textAlignment = title_alignment;
            alert_vc_message.font = [UIFont fontWithName:@"PingFangSC" size:KFitWidth(14)];
        }

        // 修改message 对齐方式

        //    UILabel *alert_vc_title = subView5.subviews[0];
        if ([subView5.subviews[2] isKindOfClass:[UILabel class]]) {
            UILabel *alert_vc_message = subView5.subviews[2];
            alert_vc_message.textAlignment = text_alignment;
            alert_vc_message.font = [UIFont fontWithName:@"PingFangSC" size:KFitWidth(14)];
        }

    } else {
        UIView *subView6 = subView5.subviews[1];
        UIView *subView7 = subView6.subviews[0];
        //    UILabel *alert_vc_title = subView5.subviews[0];
        if ([subView7.subviews[0] isKindOfClass:[UILabel class]]) {
            UILabel *alert_vc_message = subView7.subviews[0];
            alert_vc_message.textAlignment = title_alignment;
            alert_vc_message.font = [UIFont fontWithName:@"PingFangSC" size:KFitWidth(14)];
        }

        if ([subView7.subviews[1] isKindOfClass:[UILabel class]]) {
            UILabel *alert_vc_message = subView7.subviews[1];
            alert_vc_message.textAlignment = text_alignment;
            alert_vc_message.font = [UIFont fontWithName:@"PingFangSC" size:KFitWidth(14)];
        }
    }

    if (!judgeStringIsNULL(cancel_title)) {    // 添加取消按钮
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:cancel_title
                                                         style:UIAlertActionStyleCancel
                                                       handler:^(UIAlertAction *_Nonnull action) {
                                                         cancel_click_block();
                                                       }];

        [cancel setValue:cancelColor forKey:@"titleTextColor"];
        [alert_vc addAction:cancel];
    }
    if (!judgeStringIsNULL(sure_title)) {    // 添加确定按钮
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:sure_title
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction *_Nonnull action) {
                                                         sure_click_block();
                                                       }];
        [cancel setValue:sureColor forKey:@"titleTextColor"];
        [alert_vc addAction:cancel];
    }

    [vc presentViewController:alert_vc animated:YES completion:nil];
}

+ (NSString *)loopsIntExplain:(UInt32)loopsInt {
    NSString *loop;
    if ((loopsInt & 1) == 1) {
        loop = @"1";
    } else {
        loop = @"0";
    }
    if ((loopsInt >> 1 & 1) == 1) {
        loop = [NSString stringWithFormat:@"%@%@", loop, @"1"];
    } else {
        loop = [NSString stringWithFormat:@"%@%@", loop, @"0"];
    }
    if ((loopsInt >> 2 & 1) == 1) {
        loop = [NSString stringWithFormat:@"%@%@", loop, @"1"];
    } else {
        loop = [NSString stringWithFormat:@"%@%@", loop, @"0"];
    }
    if ((loopsInt >> 3 & 1) == 1) {
        loop = [NSString stringWithFormat:@"%@%@", loop, @"1"];
    } else {
        loop = [NSString stringWithFormat:@"%@%@", loop, @"0"];
    }
    if ((loopsInt >> 4 & 1) == 1) {
        loop = [NSString stringWithFormat:@"%@%@", loop, @"1"];
    } else {
        loop = [NSString stringWithFormat:@"%@%@", loop, @"0"];
    }
    if ((loopsInt >> 5 & 1) == 1) {
        loop = [NSString stringWithFormat:@"%@%@", loop, @"1"];
    } else {
        loop = [NSString stringWithFormat:@"%@%@", loop, @"0"];
    }
    if ((loopsInt >> 6 & 1) == 1) {
        loop = [NSString stringWithFormat:@"%@%@", loop, @"1"];
    } else {
        loop = [NSString stringWithFormat:@"%@%@", loop, @"0"];
    }

    NSLog(@"%@", loop);
    return loop;
}

+ (NSDictionary *)getTimeSub:(NSString *)loops {
    //    NSDictionary *dic =[NSDictionary dictionary];

    UInt32 loopsInt = 0;
    NSString *s1 = [loops substringWithRange:NSMakeRange(0, 1)];
    NSString *s2 = [loops substringWithRange:NSMakeRange(1, 1)];
    NSString *s3 = [loops substringWithRange:NSMakeRange(2, 1)];
    NSString *s4 = [loops substringWithRange:NSMakeRange(3, 1)];
    NSString *s5 = [loops substringWithRange:NSMakeRange(4, 1)];
    NSString *s6 = [loops substringWithRange:NSMakeRange(5, 1)];
    NSString *s7 = [loops substringWithRange:NSMakeRange(6, 1)];
    NSString *timeStr = @"";

    if ([s1 isEqual:@"1"]) {
        timeStr = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ %@", timeStr, NSLocalizedString(@"周一", nil)] : NSLocalizedString(@"周一", nil);
        loopsInt += 1;
    }
    if ([s2 isEqual:@"1"]) {
        timeStr = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ %@", timeStr, NSLocalizedString(@"周二", nil)] : NSLocalizedString(@"周二", nil);
        loopsInt += 2;
    }
    if ([s3 isEqual:@"1"]) {
        timeStr = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ %@", timeStr, NSLocalizedString(@"周三", nil)] : NSLocalizedString(@"周三", nil);
        loopsInt += 4;
    }
    if ([s4 isEqual:@"1"]) {
        timeStr = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ %@", timeStr, NSLocalizedString(@"周四", nil)] : NSLocalizedString(@"周四", nil);
        loopsInt += 8;
    }
    if ([s5 isEqual:@"1"]) {
        timeStr = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ %@", timeStr, NSLocalizedString(@"周五", nil)] : NSLocalizedString(@"周五", nil);
        loopsInt += 16;
    }
    if ([s6 isEqual:@"1"]) {
        timeStr = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ %@", timeStr, NSLocalizedString(@"周六", nil)] : NSLocalizedString(@"周六", nil);
        loopsInt += 32;
    }
    if ([s7 isEqual:@"1"]) {
        timeStr = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ %@", timeStr, NSLocalizedString(@"周日", nil)] : NSLocalizedString(@"周日", nil);
        loopsInt += 64;
    }

    if ([loops isEqual:@"0000011"]) {
        timeStr = NSLocalizedString(@"周末", nil);
    } else if ([loops isEqual:@"1111100"]) {
        timeStr = NSLocalizedString(@"工作日", nil);
    } else if ([loops isEqual:@"1111111"]) {
        timeStr = NSLocalizedString(@"每天", nil);
    } else {
        if (timeStr.length == 0) {
            timeStr = NSLocalizedString(@"执行一次", nil);
        }
    }
    return @{@"loopsInt" : @(loopsInt), @"timeStr" : timeStr};
    //    NSLog(@"%d",self.loopsInt);
    //    [self.timeBtn setTitle:NSLocalizedString(@"重复周期",nil) subTitle:timeStr img:@"" hidden:NO];
}
+ (NSString *)getNoDisturbingPeriodTimeSub:(NSString *)loops {
    NSString *s1 = [loops substringWithRange:NSMakeRange(0, 1)];
    NSString *s2 = [loops substringWithRange:NSMakeRange(1, 1)];
    NSString *s3 = [loops substringWithRange:NSMakeRange(2, 1)];
    NSString *s4 = [loops substringWithRange:NSMakeRange(3, 1)];
    NSString *s5 = [loops substringWithRange:NSMakeRange(4, 1)];
    NSString *s6 = [loops substringWithRange:NSMakeRange(5, 1)];
    NSString *s7 = [loops substringWithRange:NSMakeRange(6, 1)];
    NSString *timeStr = @"";

    if ([s1 isEqual:@"1"]) {
        timeStr = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ %@", timeStr, NSLocalizedString(@"周一", nil)] : NSLocalizedString(@"周一", nil);
    }
    if ([s2 isEqual:@"1"]) {
        timeStr = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ %@", timeStr, NSLocalizedString(@"周二", nil)] : NSLocalizedString(@"周二", nil);
    }
    if ([s3 isEqual:@"1"]) {
        timeStr = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ %@", timeStr, NSLocalizedString(@"周三", nil)] : NSLocalizedString(@"周三", nil);
    }
    if ([s4 isEqual:@"1"]) {
        timeStr = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ %@", timeStr, NSLocalizedString(@"周四", nil)] : NSLocalizedString(@"周四", nil);
    }
    if ([s5 isEqual:@"1"]) {
        timeStr = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ %@", timeStr, NSLocalizedString(@"周五", nil)] : NSLocalizedString(@"周五", nil);
    }
    if ([s6 isEqual:@"1"]) {
        timeStr = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ %@", timeStr, NSLocalizedString(@"周六", nil)] : NSLocalizedString(@"周六", nil);
    }
    if ([s7 isEqual:@"1"]) {
        timeStr = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ %@", timeStr, NSLocalizedString(@"周日", nil)] : NSLocalizedString(@"周日", nil);
    }

    if ([loops isEqual:@"0000011"]) {
        timeStr = NSLocalizedString(@"周末", nil);
    } else if ([loops isEqual:@"1111100"]) {
        timeStr = NSLocalizedString(@"工作日", nil);
    } else if ([loops isEqual:@"1111111"]) {
        timeStr = NSLocalizedString(@"每天", nil);
    }
    return timeStr;
}

+ (NSString *)reverseStringAction:(NSString *)loops {
    NSMutableString *reverseString = [NSMutableString string];
    for (int i = 0; i < loops.length; i++) {
        // 倒序读取字符并且存到可变数组数组中
        unichar c = [loops characterAtIndex:loops.length - i - 1];
        [reverseString appendFormat:@"%c", c];
    }
    return reverseString ?: @"";
}

@end
